﻿using CommHelper;
using Newtonsoft.Json;
using NX5Web.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Results;
using static NX5Web.Controllers.DoubaoController;

namespace NX5Web.Controllers
{
    public class WordController : BaseApiController
    {
        public class InputWord
        {
            public String Word { set; get; }
            public Int32 SentenceId { set; get; }
        }

        public class AudioFile
        {
            public String Url { set; get; }
        }

        public class WordResponseDetail
        {
            public String Audio { set; get; }
            public String Mean { set; get; }
            public String PS { set; get; }

            private List<MethodItem> _Methods = new List<MethodItem>();
            public List<MethodItem> Methods
            {
                set { _Methods = value; }
                get { return _Methods; }
            }
        }

        public class MethodItem
        {
            public String Method { set; get; }
            public String Detail { set; get; }
        }

        public class WordInfo
        {
            public Int32 ID { set; get; }
            public String Mean { set; get; }
            public String Word { set; get; }
            private List<Int32> _Index = new List<int>();
            public List<Int32> Index { set { _Index = value; } get { return _Index; } }
            public Boolean IsExt { set; get; }
        }

        public class SentenceInfo
        {
            public Int32 ID { set; get; }
        }

        [HttpPost]
        public IHttpActionResult ResetWordIndex(SentenceInfo SI)
        {
            DataManager dm = new DataManager();
            DataTable dt = dm.SqlCmd("SELECT * FROM Cus_BookWord_Sentence where ID = " + SI.ID).table;
            string pattern = "^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$";
            DataRow dr = dt.Rows[0];

            Int32 SentenceId = Int32.Parse(dr["ID"].ToString());
            DataTable AllWords = dm.SqlCmd("select CB.ID,BW.Word,CB.Mean,CB.BookId from Cus_BookWord CB INNER JOIN Base_Words BW ON CB.BaseWordID = BW.ID where SentenceId = " + SentenceId).table;


            String En = dr["SentenceEn"].ToString();

            List<String> SenWords = En.Split(' ').ToList();

            List<WordInfo> WordIds = new List<WordInfo>();

            foreach (DataRow EachWord in AllWords.Rows)
            {
                String Word = EachWord["Word"].ToString();
                String Mean = EachWord["Mean"].ToString();
                Int32 WordId = Int32.Parse(EachWord["ID"].ToString());
                Boolean IsExt = (Int32.Parse(EachWord["BookId"].ToString()) == 34 ? true : false);
                //Console.WriteLine(Word);
                WordInfo item = new WordInfo();
                item.ID = WordId;
                item.Mean = Mean;
                item.Word = Word;
                item.IsExt = IsExt;
                //WordId.ID
                for (Int32 i = 1; i <= SenWords.Count; i++)
                {
                    String SE = Regex.Replace(SenWords[i - 1], pattern, "");
                    if (SE.ToLower() == Word.ToLower())
                    {
                        item.Index.Add(i);
                    }
                }
                WordIds.Add(item);
            }

            dm.Procedure("Cus_ChangeSentenceWordIndex", "[{\"SentenceId\":" + dr["ID"].ToString()
                        + ",\"WordIds\":\"" + TransData.Tran(JsonConvert.SerializeObject(WordIds)) + "\"}]");
            Console.WriteLine(SentenceId + "=====================>OK");

            return ReturnSuccess(JsonConvert.SerializeObject(WordIds));
        }

        [HttpPost]
        public async Task<IHttpActionResult> MatchWord(InputWord input)
        {
            String RSP = "";

            DataManager dm = new DataManager();
            DataToInfo dt = new DataToInfo();
            dt = dm.Procedure("Cus_CreateExtWords", "[{\"Word\":\"" + TransData.Tran(input.Word) + "\",\"SentenceId\":" + input.SentenceId + "}]");

            if (dt.table != null && dt.table.Rows.Count > 0)
            {
                //找到了,直接返回
                return ReturnSuccess(dt.table);
            }
            else
            {

                try
                {
                    AINormal AN = new AINormal();
                    AN.Text = "我需要\"" + input.Word + "\"这个单词的意思，音标，记忆方法(优先音节记忆和词根词缀)，最少给5种记忆方法。返回json格式:{\"Methods\":[{\"Method\":方法名,\"Detail\":说明}],\"Mean\":意思,\"PS\":音标}。不要解释";

                    AudioRequest AR = new AudioRequest();
                    AR.Text = input.Word;
                    DoubaoController dc = new DoubaoController();
                    HttpResponseMessage Audio = await dc.AIAudio(AR);
                    var responseBody = await Audio.Content.ReadAsStringAsync();
                    AudioFile AF = Newtonsoft.Json.JsonConvert.DeserializeObject<AudioFile>(responseBody);
                    HttpResponseMessage WID = await dc.AIText(AN);
                    responseBody = await WID.Content.ReadAsStringAsync();
                    RSP = responseBody.Replace("{\"data\":\"", "").Replace("\"}\"}", "\"}");
                    //dm.SqlTrack("", "2", Newtonsoft.Json.JsonConvert.SerializeObject(RSP));
                    WordResponseDetail WR = Newtonsoft.Json.JsonConvert.DeserializeObject<WordResponseDetail>(RSP);

                    //dm.SqlTrack("", "1", RSP)
                    //dm.SqlTrack("", "2", Newtonsoft.Json.JsonConvert.SerializeObject(WR.Methods));

                    WR.Audio = "https://nx5.abc5g.com" + AF.Url;

                    //return null;
                    DataToInfo Result = dm.Procedure("Cus_BaseWordCreated", "[{\"Word\":\"" + TransData.Tran(input.Word)
                        + "\",\"Mean\":\"" + TransData.Tran(WR.Mean)
                        + "\",\"PS\":\"" + WR.PS
                        + "\",\"MP3\":\"" + WR.Audio
                        + "\",\"Methods\":\"" + TransData.Tran(Newtonsoft.Json.JsonConvert.SerializeObject(WR.Methods))
                        + "\",\"SentenceId\":" + input.SentenceId + "}]");
                    return ReturnSuccess(Result.table);
                }
                catch (Exception ex)
                {
                    //dm.SqlTrack("", "error", RSP);
                    return ReturnFail(ex.ToString() + "===========>" + RSP);
                }
            }
        }
    }
}